/**
 * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
 * This file is part of CSipSimple.
 *
 *  CSipSimple is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  If you own a pjsip commercial license you can also redistribute it
 *  and/or modify it under the terms of the GNU Lesser General Public License
 *  as an android library.
 *
 *  CSipSimple is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with CSipSimple.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.hermit.qmst.csipsimple.ui.outgoingcall;

import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.hermit.qmst.csipsimple.api.SipManager;
import com.hermit.qmst.csipsimple.api.SipProfile;
import com.hermit.qmst.csipsimple.utils.Compatibility;
import com.hermit.qmst.csipsimple.utils.Log;
import com.hermit.qmst.csipsimple.utils.PreferencesProviderWrapper;
import com.hermit.qmst.R;
import com.hermit.qmst.csipsimple.api.ISipService;

public class OutgoingCallChooser extends SherlockFragmentActivity {

	private String TAG = "OutgoingCallChooser";
	private Window mWindow;
    private static final String THIS_FILE = "OutgoingCallChooser";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        resetInternals();
        
        // Sanity check
        if (TextUtils.isEmpty(getPhoneNumber())) {
            Log.e(THIS_FILE, "No number detected for : " + getIntent().getAction());
            finish();
            return;
        }
        
        mWindow = getWindow();
		mWindow.requestFeature(3);
        
        setContentView(R.layout.outgoing_account_list);
        initCallOptions();
        connectService();
    }
    
    private String phoneNumber = null;
    private boolean ignoreRewritingRules = false;
    private Long accountToCallTo = null;
    
    
    private final static String SCHEME_CSIP = SipManager.PROTOCOL_CSIP;
    private final static String SCHEME_IMTO = "imto";
    private final static String SCHEME_SMSTO = "smsto";
    private final static String AUTHORITY_CSIP = SipManager.PROTOCOL_CSIP;
    private final static String AUTHORITY_SIP = SipManager.PROTOCOL_SIP;
    private final static String AUTHORITY_SKYPE = "skype";
    
    /**
     * Get the phone number that raised this activity.
     * @return The phone number we are trying to call with this activity
     */
    public String getPhoneNumber() {
        if(phoneNumber == null) {
            Intent it = getIntent();
            // First step is to retrieve the number that was asked to us.
            phoneNumber = PhoneNumberUtils.getNumberFromIntent(getIntent(), this);
            if (phoneNumber == null) {
                String action = it.getAction();
                Uri data = it.getData();
                if (action != null && data != null) {
                    String scheme = data.getScheme();
                    if(scheme != null) {
                        scheme = scheme.toLowerCase();
                    }
                    
                    if (action.equalsIgnoreCase(Intent.ACTION_SENDTO)) {
                        // Send to action -- could be im or sms
                        if (SCHEME_IMTO.equals(scheme)) {
                            // Im sent
                            String auth = data.getAuthority();
                            if (AUTHORITY_CSIP.equals(auth) ||
                                    AUTHORITY_SIP.equals(auth) ||
                                    AUTHORITY_SKYPE.equals(auth) ) {
                                phoneNumber = data.getLastPathSegment();
                            }
                        }else if (SCHEME_SMSTO.equals(scheme)) {
                            phoneNumber = PhoneNumberUtils.stripSeparators(data.getSchemeSpecificPart());
                        }
                    } else {
                        // Simple call intent
                       phoneNumber = data.getSchemeSpecificPart();
                       if(SCHEME_CSIP.equals(scheme)) {
                           ignoreRewritingRules = true;
                       }
                    } 
                }
            } else {
                String action = it.getAction();

                Uri data = it.getData();
                if (action != null && data != null) {
                    String scheme = data.getScheme();
                    if(scheme != null) {
                        scheme = scheme.toLowerCase();
                        if(SCHEME_SMSTO.equals(scheme) || "tel".equals(scheme)) {
                            phoneNumber = PhoneNumberUtils.stripSeparators(phoneNumber);
                        }
                    }
                }
            }
            // Still null ... well make it empty.
            if(phoneNumber == null) {
                phoneNumber = "";
            }
            return phoneNumber;
        }
        
        return phoneNumber;
    }
    
    /**
     * Should we ignore rewriting rules
     * @return True if rewriting rules are not taken into account for this outgoing call.
     */
    public boolean shouldIgnoreRewritingRules() {
        // Ignore rewriting rule is get once phone number is retrieved
        getPhoneNumber();
        
        return ignoreRewritingRules;
    }
    
    /**
     * Get the account to force use for outgoing.
     * @return The account id to use for outgoing. {@link SipProfile#INVALID_ID} if no account should be used.
     */
    public long getAccountToCallTo() {
        if(accountToCallTo == null) {
            accountToCallTo = getIntent().getLongExtra(SipProfile.FIELD_ACC_ID, SipProfile.INVALID_ID);
        }
        return accountToCallTo;
    }
    
    /* Service connection */
    /**
     * Connect to sip service by flagging itself as the component to consider as outgoing activity
     */
    private void connectService() {
        PreferencesProviderWrapper prefsWrapper = new PreferencesProviderWrapper(this);
        Intent sipService = new Intent(SipManager.INTENT_SIP_SERVICE);
        if (prefsWrapper.isValidConnectionForOutgoing()) {
            sipService.putExtra(SipManager.EXTRA_OUTGOING_ACTIVITY, getComponentName());
            startService(sipService);
        }
        bindService(sipService, connection, Context.BIND_AUTO_CREATE);
    }
    /**
     * Get connected sip service.
     * @return connected sip service from the activity if already connected. Null else.
     */
    public ISipService getConnectedService() {
        return service;
    }
    
    private ISipService service = null;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName component, IBinder binder) {
            service = ISipService.Stub.asInterface(binder);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            service = null;
        }
    };
    
    @TargetApi(5)
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0
                && !Compatibility.isCompatible(5)) {
            onBackPressed();

        }
        return super.onKeyDown(keyCode, event);
    }

    public void onBackPressed() {
        finishServiceIfNeeded(false);
    }
    
    /**
     * Finish the activity and send unregistration to service as outgoing activity.
     * @param defer If true the activity will ask sip service to remain active until end of next call (because it will initiate a call).
     * If false, ask sip service to consider outgoing mode as not anymore valid right now. Usually cause call will be managed another way than a sip way.
     */
    public void finishServiceIfNeeded(boolean defer) {
        Intent intent = new Intent(defer ? SipManager.ACTION_DEFER_OUTGOING_UNREGISTER : SipManager.ACTION_OUTGOING_UNREGISTER);
        intent.putExtra(SipManager.EXTRA_OUTGOING_ACTIVITY, getComponentName());
        sendBroadcast(intent);
        finish();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        resetInternals();
        try {
            unbindService(connection);
        } catch (Exception e) {
        }
    }
    
    private void resetInternals() {
        phoneNumber = null;
        accountToCallTo = null;
        ignoreRewritingRules = false;
    }
    
    
    private void initCallOptions(){
//    	addRow(getString(R.string.use_1xin), getResources().getDrawable(R.drawable.ic_launcher), new View.OnClickListener(){
//			public void onClick(View paramAnonymousView){
//				Intent _Intent = new Intent(OutgoingCallChooser.this,CallWaitActivity.class);
//				_Intent.putExtra("phone", phoneNumber);
//				startActivity(_Intent);
//				OutgoingCall.ignoreNext = "";
//				finishServiceIfNeeded(false);
//				//finish();
//	        }
//	    });
//
//    	addRow(getString(R.string.use_1xin2), getResources().getDrawable(R.drawable.ic_launcher), new View.OnClickListener(){
//			public void onClick(View paramAnonymousView){
//				OutgoingCall.ignoreNext = "";
//				try {
//					service.makeCall(phoneNumber, (int)Common.account_id);
//					finishServiceIfNeeded(true);
//				} catch (RemoteException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//
//	        }
//	    });
    	
//		addRow(getString(R.string.use_pstn), getResources().getDrawable(R.drawable.btn_call_bg), new View.OnClickListener(){
//			public void onClick(View paramAnonymousView){
//
//
//				Intent _Intent = new Intent("android.intent.action.CALL");
//				_Intent.setData(Uri.parse("tel:" + phoneNumber));
//
//				startActivity(_Intent);
//
//				finishServiceIfNeeded(false);
//				//finish();
//
//	        }
//	    });
//		mWindow.setFeatureDrawableResource(3, 17301558);
//		setTitle(getString(R.string.outgoing_call_chooser_call_text));
    }
    
	private void addRow(CharSequence pCharSequence, Drawable pDrawable, View.OnClickListener pOnClickListener){
		
//	    Log.d("SIP OUTChoose", "Append ROW " + pCharSequence);
//	    TypedArray localTypedArray = obtainStyledAttributes(16973829, new int[] { 16842829 });
//	    int i = localTypedArray.getDimensionPixelSize(0, 0);
//	    localTypedArray.recycle();
//	    LinearLayout localLinearLayout1 = (LinearLayout)findViewById(R.id.acc_list_chooser_wrapper);
//	    ImageView localImageView1 = new ImageView(this);
//	    localImageView1.setImageResource(R.drawable.divider_horizontal_dark);
//	    localImageView1.setScaleType(ImageView.ScaleType.FIT_XY);
//	    localLinearLayout1.addView(localImageView1, new ViewGroup.LayoutParams(-1, 1));
//	    LinearLayout localLinearLayout2 = new LinearLayout(this);
//	    localLinearLayout2.setFocusable(true);
//	    localLinearLayout2.setClickable(true);
//	    localLinearLayout2.setOrientation(0);
//	    localLinearLayout2.setGravity(16);
//	    //localLinearLayout2.setBackgroundResource(17301605);
//	    ImageView localImageView2 = new ImageView(this);
//	    localImageView2.setImageDrawable(pDrawable);
//	    localImageView2.setScaleType(ImageView.ScaleType.FIT_XY);
//	    LinearLayout.LayoutParams localLayoutParams = new LinearLayout.LayoutParams(48, 48);
//	    localLayoutParams.setMargins(6, 6, 6, 6);
//	    localLinearLayout2.addView(localImageView2, localLayoutParams);
//	    TextView localTextView = new TextView(this);
//	    localTextView.setText(pCharSequence);
//	    //localTextView.setTextAppearance(this, 16973892);
//	    localTextView.setTypeface(Typeface.DEFAULT_BOLD);
//	    localLinearLayout2.addView(localTextView, new ViewGroup.LayoutParams(-1, -2));
//	    localLinearLayout2.setOnClickListener(pOnClickListener);
//	    localLinearLayout1.addView(localLinearLayout2, new ViewGroup.LayoutParams(-1, i));
	  }
}
